package com.tx.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.$Gson$Preconditions;
import com.tx.entity.*;
import com.tx.service.*;
import com.tx.utils.PageUtils;
import com.tx.utils.StringUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: tcx
 * @description: 博客管理控制器
 * @Date: 2019/11/5
 **/
@Controller("blogController")
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private UserService userService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private LunBoService lunBoService;
    @Autowired
    private ReplyService replyService;
    /* *
     * @description:  打开添加博客页面
     * @author tcx
     * @date 2019/11/7
     * @param map
     * @return java.lang.String
     */
    @RequestMapping("/to_add")
    public String toAdd(Map<String,Object> map){
        //将博客分类传递到页面
        Type type = new Type();
        type.settState(1);
        map.put("type",typeService.getAll(type));
        //跳转到添加博客页面
        return "/addBlog";
    }
    /* *
     * @description:  添加博客
     * @author tcx
     * @date 2019/11/10
     * @param blog
     * @return java.lang.String
     */
    @RequestMapping("/add")
    public String add(Blog blog,HttpSession session){
        //从session里获得登录的用户
        User user = (User) session.getAttribute("user");
        //获取用户id存入数据库
        blog.setuId(user.getuId());
        //添加博客
        blogService.add(blog);
        return "/success";
    }
    /* *
     * @description:  打开首页
     * @author tcx
     * @date 2019/11/10
     * @param map
     * @param session
     * @return java.lang.String
     */
    @RequestMapping("/index")
    public String index(Map<String,Object> map, HttpSession session){
        //将博客类型存入session中
        Type type = new Type();
        type.settState(1);
        session.setAttribute("types",typeService.getAll(type));
        //将最新的博客放入map中
        map.put("blogNew",blogService.getNew());
        //将轮播图放入map中
        map.put("lunbo",lunBoService.getAll());
        return "/index";
    }
    /* *
     * @description:  显示博客列表
     * @author tcx
     * @date 2019/11/10
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/list",params = "currentPage")
    public String bloglist(Map<String,Object> map,Integer currentPage ){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将博客信息传递到博客列表传递到页面
        Result result = blogService.getBlogByPage(page);
        page = result.getPage();
        List<Blog> list = result.getList();
        map.put("blist",list);
        map.put("pageInfo",page);
        //将分页信息传递到页面
        return "/bloglist";
    }
    /* *
     * @description:  通过博客类型搜索博客
     * @author tcx
     * @date 2019/11/10
     * @param map
     * @param currentPage
     * @param tId
     * @return java.lang.String
     */
    @RequestMapping(value = "/typelist")
    public String bloglist(Map<String,Object> map, @RequestParam("currentPage") Integer currentPage, @RequestParam Integer tId){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将博客信息传递到博客列表传递到页面
        Result result = blogService.getBlogByTypePage(page,tId);
        page = result.getPage();
        List<Blog> list = result.getList();
        map.put("blist",list);
        map.put("pageInfo",page);
        map.put("tId",tId);
        //将分页信息传递到页面
        return "/bloglistByType";
    }
    /* *
     * @description: 通过关键字搜索博客
     * @author tcx
     * @date 2019/11/10
     * @param map
     * @param currentPage
     * @param title
     * @return java.lang.String
     */
    @RequestMapping("/listKey")
    public String blogKey(Map<String,Object> map, @RequestParam("currentPage") Integer currentPage, @RequestParam String title){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将博客信息传递到博客列表传递到页面
        Result result = blogService.getAllByKey(page,title);
        page = result.getPage();
        List<Blog> list = result.getList();
        map.put("blist",list);
        map.put("pageInfo",page);
        map.put("key",title);
        //将分页信息传递到页面
        return "/bloglistByKey";
    }
    /* *
     * @description:  显示博客内容
     * @author tcx
     * @date 2019/11/10
     * @param bId
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/content",params = "bId")
    public String blogContent(Integer bId,Map<String,Object> map){
        //将博客信息返回到博客详情页
        map.put("bContent",blogService.get(bId));
        List<Comment> list = blogService.getCommentByBlog(bId);
        //将评论信息返回到博客详情页
        map.put("comment",list);
        //将这篇博客所有回复信息查询出来
        List<Reply> repList=replyService.getReplyByBlog(bId);
        map.put("reply",repList);
        return "/blogcontent";
    }
    /* *
     * @description:  添加评论
     * @author tcx
     * @date 2019/11/10
     * @param session
     * @param comment
     * @return java.lang.String
     */
    @RequestMapping("/addComment")
    public String addComment(HttpSession session,Comment comment){
        //从session中获得当前登录用户
        User user = (User) session.getAttribute("user");
        //设置发表评论用户id
        comment.setuId(user.getuId());
        //添加评论
        blogService.addComment(comment);
        return "redirect:/blog/content.do?bId="+comment.getbId();
    }
    /* *
     * @description:  添加评论回复
     * @author tcx
     * @date 2019/11/10
     * @param session
     * @param comment
     * @return java.lang.String
     */
    /*@RequestMapping("/addReply")
    public String addReply(HttpSession session,Reply reply){
        //从session中获得当前登录用户
        User user = (User) session.getAttribute("user");
        //设置发表评论回复用户id
        reply.setRuId(user.getuId());
        //添加评论回复
        replyService.add(reply);
        return "redirect:/blog/content.do?bId="+reply.getrBId();
    }*/
    @ResponseBody
    @RequestMapping("/addReply")
    public String addReply(HttpSession session,Reply reply){
        //从session中获得当前登录用户
        User user = (User) session.getAttribute("user");
        //设置发表评论回复用户id
        reply.setRuId(user.getuId());
        //添加评论回复
        int total = replyService.add(reply);
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        if (total>0){
            map.put("code",200);
            map.put("msg","回复成功");
        } else {
            map.put("code",-1);
            map.put("msg","回复失败");
        }
        return gson.toJson(map);
    }

    /*******************************************管理后台界面******************************************/
    /* *
     * @description:  打开管理博客界面,分页查询
     * @author tcx
     * @date 2019/11/10
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/to_list",params = "currentPage")
    public String toList(Map<String,Object> map,HttpSession session,Integer currentPage){
        //拿到用户
        User user = (User) session.getAttribute("user");
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将博客信息传递到博客列表传递到页面
        Result result = blogService.getAllByUser(page,user.getuId());
        page = result.getPage();
        List<Blog> list = result.getList();
        //查询出用户博客，存入页面
        map.put("bloglist",list);
        map.put("pageInfo",page);
        //查出博客总数
        map.put("count",blogService.getByUserCount(user.getuId()));
        //跳转到管理博客列表界面
        return "/student_bloglist";
    }
    /* *
     * @description:  打开修改界面
     * @author tcx
     * @date 2019/11/10
     * @param uId
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/to_update",params = "bId")
    public String edit(Integer bId,Map<String,Object> map){
        Type type = new Type();
        type.settState(1);
        //获取所有博客类型
        map.put("typelist",typeService.getAll(type));
        //获取博客数据
        map.put("blog",blogService.get(bId));
        return "student_blogedit";
    }
    /* *
     * @description:  修改博客
     * @author tcx
     * @date 2019/11/10
     * @param blog
     * @return java.lang.String
     */
    @RequestMapping("/student/updateblog")
    public String update(Blog blog){
        blogService.edit(blog);
        return "redirect:/blog/student/to_list.do?currentPage=1";
    }
    /* *
     * @description:  删除博客
     * @author tcx
     * @date 2019/11/10
     * @param bId
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/removeold",params = "bId")
    public String remove(Integer bId){
        blogService.remove(bId);
        return "redirect:/blog/student/to_list.do?currentPage=1";
    }
    /* *
     * @description:  删除博客
     * @author tcx
     * @date 2019/11/22
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/student/remove")
    public String remove(HttpServletRequest request){
        Integer bId = Integer.parseInt(request.getParameter("bId"));
        blogService.remove(bId);
        JSONObject json = new JSONObject();
        return json.toString();
    }
    /* *
     * @description:  打开用户设置界面
     * @author tcx
     * @date 2019/11/16
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/student/to_studentSet")
    public String toUserSet(Map<String,Object> map,HttpSession session){
        User user=(User)session.getAttribute("user");
        map.put("uId",user.getuId());
        return "student_set";
    }
    /* *
     * @description:  打开用户主页
     * @author tcx
     * @date 2019/11/16
     * @param map
     * @param uId
     * @return java.lang.String
     */
    @RequestMapping(value = "/to_home",params = "uId")
    public String toHome(Map<String,Object> map,Integer uId){
        //查询用户信息
        User user = userService.get(uId);
        //查询用户十条最新博客
        List<Blog> bListNew = blogService.getUserNew(uId);
        //查询用户十条最新上传文件
        List<FileInfo> fListNew = fileInfoService.getUserNewFile(uId);
        map.put("uhome",user);
        map.put("bhome",bListNew);
        map.put("fhome",fListNew);
        return "home";
    }

    //查询原始密码是否输入正确
    @RequestMapping(value="/student/repwd")
    @ResponseBody
    public String toVerifyUsername(HttpSession session,HttpServletRequest request) {
        //获取用户id
        User user = (User) session.getAttribute("user");
        String pwd=request.getParameter("pwd");
        //查询原始密码
        Boolean flag = userService.rePwd(pwd,user);
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
            if (flag) {
                map.put("code",0);
                map.put("msg","匹配");
            } else {
                map.put("code",-1);
                map.put("msg","原始密码输入错误");
            }
            return gson.toJson(map);
    }
/*-----------------------------------------------------------后台管理博客-------------------------------------------------------*/

    @RequestMapping("/student/blog_list")
    @ResponseBody
    public String studentList(@RequestParam(value = "page", required = false) Integer currentPage,
                       @RequestParam(value = "limit", required = false) Integer rows,
                       @RequestParam(value = "keywords", required = false) String keywords,
                       @RequestParam(value = "startTime", required = false) String startTime,
                       @RequestParam(value = "endTime", required = false) String endTime,HttpSession session){
        User user= (User) session.getAttribute("user");

        Page pageBean = new Page();
        pageBean.setCurrentPage(currentPage);//设置当前页
        pageBean.setEveryPage(rows);//设置每页显示数量
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("start", pageBean.getStart());//设置起始页
        map.put("size", pageBean.getEveryPage());//设置页面大小
        map.put("q", StringUtil.formatLike(keywords));//设置查询条件
        map.put("uId", user.getuId());
        map.put("startTime", startTime);
        map.put("endTime", StringUtil.formatEndTime(endTime));
        List<Blog> list = blogService.list(map);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        Integer total = blogService.getTotal(map);//获得总数据
        map.clear();
        if(list!=null){
            map.put("data", list);
            map.put("count", total);
            map.put("code", 0);
            map.put("msg", "");

        }else{
            map.put("data", list);
            map.put("count", total);
            map.put("code", 1);
            map.put("msg", "");
        }
        return  gson.toJson(map);
    }
    /*修改博客*/
    @ResponseBody
    @RequestMapping("/teacher/admin_update")
    public String adminupdate(Blog blog,HttpSession session){
        int resultTotal = blogService.edit(blog);
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        if (resultTotal > 0) {
            map.put("code",0);
            map.put("msg","修改成功");
        } else {
            map.put("code",-1);
            map.put("msg","修改失败");
        }
        return gson.toJson(map);
    }
    /* *
     * @description:  删除博客
     * @author tcx
     * @date 2020/04/05
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/teacher/admin_delete")
    public String deleteBlog(HttpServletRequest request){
        String[] idsStr = request.getParameter("ids").split(",");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < idsStr.length; i++) {
            blogService.remove(Integer.parseInt(idsStr[i]));
        }
        map.put("msg", 200);
        return  gson.toJson(map);
    }
    /* *
     * @description:  打开我的评论
     * @author tcx
     * @date 2020/5/17
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/student/to_commlist")
    public String comm_list(){
        return "/student_commlist";
    }
    /* *
     * @description:  请求评论列表
     * @author tcx
     * @date 2020/5/17
     * @param currentPage
     * @param rows
     * @param keywords
     * @param startTime
     * @param endTime
     * @param session
     * @return java.lang.String
     */
    @RequestMapping("/student/comm_list")
    @ResponseBody
    public String commList(@RequestParam(value = "page", required = false) Integer currentPage,
                           @RequestParam(value = "limit", required = false) Integer rows,
                           @RequestParam(value = "keywords", required = false) String keywords,
                           @RequestParam(value = "startTime", required = false) String startTime,
                           @RequestParam(value = "endTime", required = false) String endTime,
                           HttpSession session){
        //获取当前登录用户
        User user = (User)session.getAttribute("user");
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        if(user!=null){
            Page pageBean = new Page();
            pageBean.setCurrentPage(currentPage);//设置当前页
            pageBean.setEveryPage(rows);//设置每页显示数量
            map.put("uId",user.getuId());
            map.put("start", pageBean.getStart());//设置起始页
            map.put("size", pageBean.getEveryPage());//设置页面大小
            map.put("q", StringUtil.formatLike(keywords));//设置查询条件
            map.put("startTime", startTime);
            map.put("endTime", StringUtil.formatEndTime(endTime));
            List<Comment> list = blogService.getCommentAll(map);
            Integer total = blogService.getTotalComm(map);//获得总数据
            map.clear();
            if(list!=null){
                map.put("data", list);
                map.put("count", total);
                map.put("code", 0);
                map.put("msg", "");

            }else{
                map.put("data", list);
                map.put("count", total);
                map.put("code", 1);
                map.put("msg", "");
            }
        }else{

        }
        return  gson.toJson(map);
    }
    /* *
     * @description:  删除评论
     * @author tcx
     * @date 2020/04/05
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/student/comm_delete")
    public String deleteComm(HttpServletRequest request){
        String[] idsStr = request.getParameter("ids").split(",");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < idsStr.length; i++) {
            blogService.removeComm(Integer.parseInt(idsStr[i]));
        }
        map.put("msg", 200);
        return  gson.toJson(map);
    }
    /* *
     * @description:  打开我的回复
     * @author tcx
     * @date 2020/5/17
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/student/to_replylist")
    public String reply_list(){
        return "/student_replylist";
    }
    /* *
     * @description:  请求评回复论列表
     * @author tcx
     * @date 2020/5/17
     * @param currentPage
     * @param rows
     * @param keywords
     * @param startTime
     * @param endTime
     * @param session
     * @return java.lang.String
     */
    @RequestMapping("/student/reply_list")
    @ResponseBody
    public String replyList(@RequestParam(value = "page", required = false) Integer currentPage,
                           @RequestParam(value = "limit", required = false) Integer rows,
                           @RequestParam(value = "keywords", required = false) String keywords,
                           @RequestParam(value = "startTime", required = false) String startTime,
                           @RequestParam(value = "endTime", required = false) String endTime,
                           HttpSession session){
        //获取当前登录用户
        User user = (User)session.getAttribute("user");
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        if(user!=null){
            Page pageBean = new Page();
            pageBean.setCurrentPage(currentPage);//设置当前页
            pageBean.setEveryPage(rows);//设置每页显示数量
            map.put("uId",user.getuId());
            map.put("start", pageBean.getStart());//设置起始页
            map.put("size", pageBean.getEveryPage());//设置页面大小
            map.put("q", StringUtil.formatLike(keywords));//设置查询条件
            map.put("startTime", startTime);//设置开始时间
            map.put("endTime", StringUtil.formatEndTime(endTime));
            List<Reply> list = replyService.getAll(map);
            Integer total = replyService.getTotal(map);//获得总数据
            map.clear();
            if(list!=null){
                map.put("data", list);
                map.put("count", total);
                map.put("code", 0);
                map.put("msg", "");

            }else{
                map.put("data", list);
                map.put("count", total);
                map.put("code", 1);
                map.put("msg", "");
            }
        }else{

        }
        return  gson.toJson(map);
    }
    /* *
     * @description:  删除评论回复
     * @author tcx
     * @date 2020/04/05
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/student/reply_delete")
    public String deleteRep(HttpServletRequest request){
        String[] idsStr = request.getParameter("ids").split(",");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < idsStr.length; i++) {
            replyService.remove(Integer.parseInt(idsStr[i]));
            replyService.remove(Integer.parseInt(idsStr[i]));
        }
        map.put("msg", 200);
        return  gson.toJson(map);
    }

    @ResponseBody
    @RequestMapping("/student/msgCount")
    public String getMsg(HttpSession session){
        User user = (User) session.getAttribute("user");
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        if(user!=null){
            map.put("uId",user.getuId());//用户id
            Integer cCount = blogService.getComStateCount(map);//被评论总数
            Integer rCount = replyService.getCountState(map);//被回复总数
            Integer count=cCount+rCount;
            map.clear();
            map.put("msg", 200);
            map.put("msgCount",count);
            return  gson.toJson(map);
        }else{
            map.clear();
            map.put("msg", -1);
            return  gson.toJson(map);
        }
    }
    //打开评论我的消息列表
    @RequestMapping(value = "/student/to_msgCommList",params = "currentPage")
    public String to_msgCommList(Map<String,Object> map,HttpSession session,Integer currentPage){
        //拿到用户
        User user = (User) session.getAttribute("user");
        Page pageBean = new Page();
        pageBean.setCurrentPage(currentPage);//设置当前页
        Map<String, Object> mapCount = new HashMap<>();
        mapCount.put("uId",user.getuId());
        Integer count = blogService.getComStateCount(mapCount);
        pageBean = PageUtils.createPage(pageBean,count);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("start", pageBean.getBeginIndex());//设置起始页
        map1.put("size", pageBean.getEveryPage());//设置页面大小
        map1.put("ortherId",user.getuId());
        map1.put("paixu","c.c_CreateTime");
        map1.put("state",1);//未读消息
        mapCount.put("uId",user.getuId());
        //将评论信息传递到博客列表传递到页面
        List<Comment> list = blogService.getCommentAll(map1);
        map.put("commentlist",list);
        map.put("pageInfo",pageBean);
        map.put("count",count);//消息总数
        //跳转到管理博客列表界面
        return "/student_messageComm";
    }
    //打开回复我的消息列表
    @RequestMapping(value = "/student/to_msgCommReplyList",params = "currentPage")
    public String to_msgCommReplyList(Map<String,Object> map,HttpSession session,Integer currentPage){
        //拿到用户
        User user = (User) session.getAttribute("user");
        Page pageBean = new Page();
        pageBean.setCurrentPage(currentPage);//设置当前页
        Map<String, Object> mapCount = new HashMap<>();
        mapCount.put("uId",user.getuId());
        Integer count = replyService.getCountState(mapCount);
        pageBean = PageUtils.createPage(pageBean,count);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("start", pageBean.getBeginIndex());//设置起始页
        map1.put("size", pageBean.getEveryPage());//设置页面大小
        map1.put("ortherId",user.getuId());
        map1.put("paixu","r.r_createTime");
        map1.put("state",1);//未读消息
         //将评论信息传递到博客列表传递到页面
        List<Reply> list = replyService.getAll(map1);
        map.put("replylist",list);
        map.put("pageInfo",pageBean);
        map.put("count",count); //消息总数
        //跳转到管理博客列表界面
        return "/student_messageCommReply";
    }

    /* *
     * @description:  评论已读
     * @author tcx
     * @date 2020/9/13
     * @param null
     * @return
     */
    @RequestMapping(value = "/CommState")
    public String editCommState(@RequestParam(value = "bId", required = false) Integer bId,
                                @RequestParam(value = "cId", required = false) Integer cId, Map<String,Object> map){
        //将博客信息返回到博客详情页
        map.put("bContent",blogService.get(bId));
        List<Comment> list = blogService.getCommentByBlog(bId);
        //将评论信息返回到博客详情页
        map.put("comment",list);
        //将这篇博客所有回复信息查询出来
        List<Reply> repList=replyService.getReplyByBlog(bId);
        //将此条评论状态改为已读
        blogService.editCommState(cId);
        map.put("reply",repList);
        return "/blogcontent";
    }
    /* *
     * @description:  回复已读
     * @author tcx
     * @date 2020/9/13
     * @param null
     * @return
     */
    @RequestMapping(value = "/ReplyState")
    public String editReplyState(@RequestParam(value = "bId", required = false) Integer bId,
                                @RequestParam(value = "rId", required = false) Integer rId, Map<String,Object> map){
        //将博客信息返回到博客详情页
        map.put("bContent",blogService.get(bId));
        List<Comment> list = blogService.getCommentByBlog(bId);
        //将评论信息返回到博客详情页
        map.put("comment",list);
        //将这篇博客所有回复信息查询出来
        List<Reply> repList=replyService.getReplyByBlog(bId);
        //将此条评论状态改为已读
        replyService.editReplyState(rId);
        map.put("reply",repList);
        return "/blogcontent";
    }
}
